package com.example.myapplication.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.common.http.MyHttp;
import com.example.myapplication.common.http.MyHttpCallback;
import com.example.myapplication.listener.MyAnimatorListener;
import com.example.myapplication.util.SpUtil;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class SplashActivity extends AppCompatActivity implements MyHttpCallback {

    private ImageView splashLogo;
    private SpUtil spUtil;
    private MyHttp myHttp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        initView();
        initData();
    }

    private void initData() {
        spUtil = new SpUtil(this);
        myHttp = new MyHttp(this, this);
        animTogo();
    }


    /**
     * 动画进入首页
     */
    private void animTogo() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(splashLogo, "alpha", 1f, 0.1f);
        animator.setDuration(2000);
        animator.start();
        animator.addListener(new MyAnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //判断是否有用户token
                String usertoken = spUtil.getValue("userconfig", "token");
                Intent intent = new Intent();
                if (usertoken == null) {
                    //进入登录
                    intent.setClass(getApplicationContext(), LoginActivity.class);
                    startActivity(intent);
                    //从斩中清空
                    finish();
                } else {
                    //检查token是否过期
                    myHttp.queryHttpByToken("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens", usertoken);
                }

            }
        });
    }


    private void initView() {
        splashLogo = (ImageView) findViewById(R.id.splash_logo);
    }

    @Override
    public void doMessage(Message message) {
        if (message.what == MyHttp.USER_TOKEN) {
            int code = (int) message.obj;
            Log.d("zoubo", "doMessage: " + code);
            if (code == 200) {
                //token失效
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
            } else {
                startActivity(new Intent(getApplicationContext(), LoginActivity.class));
            }
        }
    }
}